package sf.model;

import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import sf.jsonloader.JsonLoader;

public class DBTableInfo {

	private static JsonLoader jsonLoader;

	private DBTableInfo() {
	}

	public static List<DBColumnInfo> getColumns(String table,
			ResultSetMetaData rsmd) throws SQLException, ClassNotFoundException {
		jsonLoader = JsonLoader.getInstance();

		List<DBColumnInfo> list = new ArrayList<DBColumnInfo>();

		int columnCount = rsmd.getColumnCount();

		for (int i = 1; i < columnCount + 1; i++) {
			String code = rsmd.getColumnName(i);
			// String label = Labels.getInstance().getColumnLabel(table, code);
			String label = getColumnLabel(table, code);
			String type = rsmd.getColumnTypeName(i);
			Class<?> cls = Class.forName(rsmd.getColumnClassName(i));
			int size = rsmd.getColumnDisplaySize(i);
			boolean isPrimaryKey = isPrimaryKey(table, code);
			// boolean isNullable = rsmd.isNullable(i) == 1 ? true : false;
			boolean isNullable = isColumnNullable(table, code);

			list.add(new DBColumnInfo(code, label, type, cls, size,
					isPrimaryKey, isNullable));
		}

		return list;
	}

	@SuppressWarnings("unchecked")
	private static HashMap getColumn(ArrayList columns, String columnCode) {
		for (Object c : columns) {
			HashMap hc = (HashMap) c;
			if (hc.get("code").equals(columnCode)) {
				return hc;
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private static String getColumnLabel(String tableName, String columnName) {
		return (String) getColumn(
				(ArrayList) jsonLoader.get(tableName, "columns"), columnName)
				.get("name");
	}

	@SuppressWarnings("unchecked")
	private static boolean isColumnNullable(String tableName, String columnName) {
		return (Boolean) getColumn(
				(ArrayList) jsonLoader.get(tableName, "columns"), columnName)
				.get("mandatory");
	}

	@SuppressWarnings("unchecked")
	private static boolean isPrimaryKey(String tableName, String columnName) {
		return (Boolean) getColumn(
				(ArrayList) jsonLoader.get(tableName, "columns"), columnName)
				.get("primary");
	}
}